#-*- coding: utf-8 -*-
import django.core.mail
from django.utils import simplejson
from django.core.mail.backends.base import BaseEmailBackend

from selenose.models import EmailMessage

class EmailBackend(BaseEmailBackend):
    
    def send_messages(self, messages):
        for message in messages:
            EmailMessage(data=jsonize(message)).save()

def jsonize(message):
    data = {'subject': message.subject,
            'body': message.body,
            'from_email': message.from_email,
            'to': message.to,
            'bcc': message.bcc,
            'attachments': message.attachments,
            'headers': message.extra_headers, }
    return simplejson.dumps(data)

def pythonize(message):
    data = simplejson.loads(message)
    return django.core.mail.EmailMessage(subject=data.get('subject'),
                                         body=data.get('body'),
                                         from_email=data.get('from_email'),
                                         to=data.get('to'),
                                         bcc=data.get('bcc'),
                                         attachments=data.get('attachments'),
                                         headers=data.get('headers'))
